namespace SimpleWebServices.Web
{
    using System;
    using System.Xml;

    public sealed class Expiration : ValueObject<Expiration>
    {
        public Expiration()
            : this(null as string)
        {
        }

        public Expiration(string value)
        {
            this.RegisterProperty(x => x.Value);

            this.Value = value;
        }

        public string Value
        {
            get;
            set;
        }

        public static implicit operator DateTime(Expiration expiration)
        {
            return (null == expiration) ? DateTime.MinValue : expiration.ToDateTime();
        }

        public static implicit operator Expiration(DateTime value)
        {
            return (null == value) ? null as Expiration : new Expiration(XmlConvert.ToString(value, XmlDateTimeSerializationMode.Utc));
        }

        public static implicit operator Expiration(TimeSpan value)
        {
            return (null == value) ? null as Expiration : new Expiration(XmlConvert.ToString(value));
        }

        public static implicit operator Expiration(string value)
        {
            return (null == value) ? null as Expiration : new Expiration(value);
        }

        public static implicit operator string(Expiration expiration)
        {
            return (null == expiration) ? null as string : expiration.Value;
        }

        public DateTime ToDateTime()
        {
            DateTime result = DateTime.MinValue;

            if (!string.IsNullOrEmpty(this.Value))
            {
                if (this.Value.StartsWith("P", StringComparison.OrdinalIgnoreCase))
                {
                    result = DateTimeFactory.UtcNow + XmlConvert.ToTimeSpan(this.Value);
                }
                else
                {
                    result = XmlConvert.ToDateTime(this.Value, XmlDateTimeSerializationMode.Utc);
                }
            }

            return result;
        }
    }
}